﻿using MediatR;
using T_Rbac_APi.Application.Command.Jobs;
using T_Rbac_Rep.Interface;

namespace T_Rbac_APi.Application.CommandHandler.JobsHandler
{
    public class JobDeleteHandlers : IRequestHandler<JobDeleteCommand, int>
    {
        private readonly IjobRep ijobRep;
        private readonly IjobMenuesRep ijobMenuesRep;
        private readonly IOperator iopeartor;

        public JobDeleteHandlers(IjobRep ijobRep, IjobMenuesRep ijobMenuesRep, IOperator iopeartor)
        {
            this.ijobRep = ijobRep;
            this.ijobMenuesRep = ijobMenuesRep;
            this.iopeartor = iopeartor;
        }

        public async Task<int> Handle(JobDeleteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var list = await iopeartor.GetvaluesByResult(x => x.Orid == request.id && !x.IsDel);
                if (list != null)
                {
                    return await Task.FromResult(-1);
                }
                var joblist = await ijobRep.GetAloneByid(request.id);
                int result = await ijobRep.Delete(joblist);
                if (result != 0)
                {
                    var jobmenues = await ijobMenuesRep.GetvaluesByResult(x => x.Jjid == request.id && !x.IsDel);
                    if (jobmenues != null)
                    {
                        await ijobMenuesRep.DeleteRange(jobmenues.ToList());
                    }
                }
                return await Task.FromResult(1);
            }
            catch (Exception)
            {
                return await Task.FromResult(-2);
                throw;
            }
        }
    }
}
